import { defineStore } from 'pinia'
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'
import type { userState } from '@/store/types/type'
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
import type { LoginFormData, LoginResponseData } from '@/api/user/types'
import { constantRoutes, asyncRoutes, anyRoutes } from '@/router/routes'
import router from '@/router'

// @ts-ignore
import cloneDeep from 'lodash/cloneDeep'

function filterAsyncRoute(asnycRoute: any, routes: any) {
    return asnycRoute.filter((item: any) => {
        if (routes.includes(item.name)) {
            if (item.children && item.children.length > 0) {
                item.children = filterAsyncRoute(item.children, routes)
            }
            return true
        }
    })
}

export const useUserStore = defineStore('user', {
    state: (): userState => {
        return {
            token: GET_TOKEN(),
            username: '',
            avatar: '',
            menuRoutes: constantRoutes,
            buttons: [],
        }
    },
    actions: {
        async userLogin(data: LoginFormData) {
            let result: LoginResponseData = await reqLogin(data)
            if (result.code === 200) {
                this.token = result.data as string
                SET_TOKEN(result.data as string)

                return 'ok'
            } else {
                return Promise.reject(new Error(result.message))
            }
        },
        async userInfo() {
            let result: any = await reqUserInfo()
            if (result.code === 200) {
                this.username = result.data.name
                this.avatar = result.data.avatar
                this.buttons = result.data.buttons

                const userAsyncRoutes = filterAsyncRoute(cloneDeep(asyncRoutes), result.data.routes)

                this.menuRoutes = [...constantRoutes, ...userAsyncRoutes, ...anyRoutes]

                const waitAddRoute = [...userAsyncRoutes, ...anyRoutes]

                waitAddRoute.forEach((route: any) => {
                    router.addRoute(route)
                })

                return 'ok'
            } else {
                return Promise.reject(new Error(result.message))
            }
        },
        async userLogout() {
            let result: any = await reqLogout()
            if (result.code === 200) {
                this.username = ''
                this.avatar = ''
                this.token = ''
                REMOVE_TOKEN()
                return 'ok'
            } else {
                return Promise.reject(new Error(result.message))
            }
        },
    },
})
